﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PubSubLite.Configuration;
using PubSubLite.Messaging.MessageChannels;

namespace PubSubLite.Messaging
{
    public class MessageChannelListener : IMessageChannelListener
    {

        public MessageChannelListener(IMessageChannelProvider channelProvider, 
            ICommandDispatcher commandDispatcher,
            IMessageDispatcher messageDispatcher)
	    {
            if (channelProvider == null)
            {
                throw new ArgumentNullException("channelProvider");
            }
            if (commandDispatcher == null)
            {
                throw new ArgumentNullException("commandDispatcher");
            }
            if (messageDispatcher == null)
            {
                throw new ArgumentNullException("messageDispatcher");
            }
            _channelProvider = channelProvider;
            _commandDispatcher = commandDispatcher;
            _messageDispatcher = messageDispatcher;
            foreach (var channel in _channelProvider.Channels)
            {
                channel.MessageReceived += new EventHandler<MessageReceivedEventArgs>(_channel_MessageReceived);
            }
	    }

        void _channel_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            if (e.Message.CorrelatingMessageID != Guid.Empty)
            {
                _commandDispatcher.DispatchReturnMessage(e.Message, e.Message.MessageDataType);
            }
            else if (e.Message.IsCommand)
            {
                _commandDispatcher.DispatchCommand(e.Message, e.Message.MessageDataType);
            }
            else
            {
                _messageDispatcher.DispatchMessage(e.Message, e.Message.MessageDataType);
            }
        }

        private IMessageChannelProvider _channelProvider;
        private IMessageDispatcher _messageDispatcher;
        private ICommandDispatcher _commandDispatcher;
        private bool _isRunning;

        void IMessageChannelListener.Start()
        {
            _isRunning = true;
        }

        void IMessageChannelListener.Stop()
        {
            _isRunning = false;
        }
    }
}
